'use strict';

var express = require('express');
var timeout = require('connect-timeout');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var AV = require('leanengine');
var ueditor = require("./public/ueditor/index");
const redisManager = require('./routes/redisManager/redisManager')
var functionTool = require('./queryFun/functionTool');

var cors = require('cors')
// 加载云函数定义，你可以将云函数拆分到多个文件方便管理，但需要在主文件中加载它们
require('./cloud');
var common = require('./cloud/common');
var app = express();

// 设置模板引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(express.static('public'));

// 设置默认超时时间
app.use(timeout('300s'));

// 加载云引擎中间件
app.use(AV.express());

app.enable('trust proxy');

//解决跨域问题
app.use(cors({credentials: true, origin: [
    'http://192.168.1.173:3000',
    'http://localhost:8010',
    'http://192.168.1.46:8009',
    'http://192.168.1.225:9898',
    'http://192.168.188.226:8009',
    'http://localhost:8002',
    'http://localhost:8009',
    'http://192.168.1.195:8002',
    'http://192.168.1.195:8010',
    'http://xws.aladada.com',
  ]}));
let urlWhite = [
  // 'getGoodsList',
  // 'getQiniuUploadToken',
  // 'getGoodsTypeList',
  // 'getProductInfo',
  // 'getCaseInfo',
  // 'getCourseInfo',
  // 'wxPayCollageNotify',
  // 'wxAuthorApplyAgency',
  // 'applyAgencyWxUrl',
  // 'wxPayForApplyAgency',
  // 'getOpenOId',
  // 'applyInfo',
  // 'fetchAllLevel',
  // 'applyForAgencyBak',
  // 'resetPasswordBySmsCode',
  // 'getVersion',
  // 'requestPasswordResetBySmsCode',
  // 'miniPhoneLogin',
  // 'miniMobileLogin',
  'mobilePhoneCheck',
  '/getOpenId',
  '/miniCheckUserAuthData',
  "/authCertificateToSignUpUser",
  "/mobile",
  "/login",
  "/logout",
  "/register",
  "/requestCode",
  "/checkPhone",
  "/phoneLogin",
  "/check/name",
  "order/wxPayNotify",
  "/1.1/functions/_ops/metadatas",
  "/__engine/",
  "admin/imgUpload",
  "isVerPhone"
]


app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(cookieParser());

app.use(AV.Cloud.CookieSession({ secret: '5353453452345@1231defaefwfaefAASEFwefqwefw35grgsrsergsrs', maxAge: 3600000*24, fetchUser: true ,resave: true,rolling:true}));
// 加载云引擎中间件
app.use(async function (req,res,next) {

 res.header("Access-Control-ALLOW-Credentials",true);

  var url = req.originalUrl;
  var urls =  urlWhite.filter(x=>{
    return url.includes(x)||url==x;
  })
  let sessionToken = req.get('sessiontoken')
  if (sessionToken&&sessionToken.length>0){
    let platForm =  req.get('platform')
    if (platForm == 'mini'){
      let result =   await  redisManager.getUserToCacheBySessionToken(sessionToken)
      if (result){
        req.currentUser = result
        // next()
        return
      }
    }

  }

  if (req.currentUser||(urls&&urls.length>0)){
      functionTool.saveRequestLog(req)
    next();
  }else{
    // console.log("8888",url);
    var rs = common.getReturnArr("", 10011, "账户已失效,如后台管理请登录：/login 如登录店铺请登录：", {});
    res.send(JSON.stringify(rs));
  }

});
// app.all('*', function(req, res, next) {
//   next()
// });

// 需要重定向到 HTTPS 可去除下一行的注释。
// app.use(AV.Cloud.HttpsRedirect());

// app.use(bodyParser.json({limit: '50mb'}));
// app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
// app.use(cookieParser());

// app.get('/', function(req, res) {
//   res.render('index', { currentTime: new Date() });
// });
app.use("/ueditor/ue", ueditor(path.join(__dirname, 'public'),{
  qn: {
    accessKey: 'AsPvgPQZqIPBojLgMm6HixsjsIz7YCEy1gNli9Zb',
    secretKey: 'cJ47G1jJPzC20260pxlt9uh4ScUV51MlU7iMvhC9',
    bucket: 'family',
    origin: 'http://tribemedia.aladada.com/'
  }
}, function (req, res, next) {
  //客户端上传文件设置
  var imgDir = '/img/ueditor/'
  var ActionType = req.query.action;
  if (ActionType === 'uploadimage' || ActionType === 'uploadfile' || ActionType === 'uploadvideo') {
    var file_url = imgDir;//默认图片上传地址
     /*其他上传格式的地址*/
    if (ActionType === 'uploadfile') {
      file_url = '/file/ueditor/'; //附件
    }
    if (ActionType === 'uploadvideo') {
      file_url = '/video/ueditor/'; //视频
    }
    res.ue_up(file_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
    res.setHeader('Content-Type', 'text/html');
  }
  //  客户端发起图片列表请求
  else if (req.query.action === 'listimage') {
    var dir_url = imgDir;
    res.ue_list(dir_url); // 客户端会列出 dir_url 目录下的所有图片
  }
  // 客户端发起其它请求
  else {
    // console.log('config.json')
    res.setHeader('Content-Type', 'application/json');
    res.redirect('/ueditor/jsp/config.json');
  }
}));
app.get('/broadcast', function(req, res) {
    res.render('index', { currentTime: new Date() });
});

// app.use(AV.Cloud.CookieSession({ secret: '<Aladada>', maxAge: 3600000, fetchUser: true }));

// 可以将一类的路由单独保存在一个文件中
app.use('/', require('./routes/index'));
// app.use('/todos', require('./routes/todos'));
app.use('/editor', require('./routes/editor'));
app.use('/getdata', require('./routes/getdata'));
app.use('/tribeRoute', require('./routes/tribeRoute'));
app.use('/qiniuCallBack', require('./routes/qiniuCallBack'));
app.use('/v1/getStoreManagementData', require('./routes/getStoreManagementData'));
app.use('/v1/smAdmin', require('./routes/smAdmin'));
app.use('/v1/smOrder', require('./routes/smOrder'));

app.use(function(req, res, next) {
  // 如果任何一个路由都没有返回响应，则抛出一个 404 异常给后续的异常处理器
  if (!res.headersSent) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
  }
  next()
});

// error handlers
app.use(function(err, req, res, next) {
  if (req.timedout && req.headers.upgrade === 'websocket') {
    // 忽略 websocket 的超时
    return;
  }

  var statusCode = err.status || 500;
  if (statusCode === 500) {
    console.error(err.stack || err);
  }
  if (req.timedout) {
    console.error('请求超时: url=%s, timeout=%d, 请确认方法执行耗时很长，或没有正确的 response 回调。', req.originalUrl, err.timeout);
  }
  res.status(statusCode);
  // 默认不输出异常详情
  var error = {};
  if (app.get('env') === 'development') {
    // 如果是开发环境，则将异常堆栈输出到页面，方便开发调试
    error = err;
  }
  res.render('error', {
    message: err.message,
    error: error
  });
});

module.exports = app;
